/**
 * *************************************
 * Copyright(c)2016 Dingdang Yixia 
 * All Rights Reserved.
 *
 * @File: AccountHandleServiceImpl.java
 * @Package: com.purchase.service.impl
 * @Description:
 * 
 * @Version: V1.0
 * @Author: Yidong.Xiang
 * @Date: 2018年6月27日 下午2:58:28
 * 
 * *************************************
 */
package com.purchase.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.fastjson.JSONObject;
import com.purchase.entity.AccountAward;
import com.purchase.entity.AccountBonus;
import com.purchase.entity.AccountIncome;
import com.purchase.entity.AppUser;
import com.purchase.entity.Member;
import com.purchase.entity.Order;
import com.purchase.entity.Vendor;
import com.purchase.entity.WxUser;
import com.purchase.mapper.AccountAwardMapper;
import com.purchase.mapper.AccountBonusMapper;
import com.purchase.mapper.AccountIncomeMapper;
import com.purchase.mapper.AppUserMapper;
import com.purchase.mapper.GoodsMapper;
import com.purchase.mapper.MemberMapper;
import com.purchase.mapper.OrderMapper;
import com.purchase.mapper.VendorMapper;
import com.purchase.mapper.WxUserMapper;
import com.purchase.model.domain.BonusAccount;
import com.purchase.model.domain.BonusVoucher;
import com.purchase.model.domain.DealResult;
import com.purchase.model.domain.IncomeDetails;
import com.purchase.model.domain.VendorTeam;
import com.purchase.service.AccountHandleService;
import com.purchase.util.DateUtil;
import com.purchase.util.LogInfo;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: AccountHandleServiceImpl.java
 * @Module: 佣金业务逻辑模块
 * @Description: 
 * 
 * @author: Yidong.Xiang
 * @date: 2018年6月27日 下午2:58:28
 * 
 */
@Slf4j
@Service("accountHandleService")
public class AccountHandleServiceImpl implements AccountHandleService {
	//销售佣金等级
	static String memberGrade = "BLA";//BLA：直属会员销售佣金
	static String vendorGrade = "BLB";//BLB：代购销售佣金
	static String supVendorGrade = "BLC";//BLC：直属代购奖金
	static String teamGrade = "BLD";//BLD：团队管理奖金（团队非直属代购|总监和总经理）
	static String directorGrade = "BLE";//BLE：培养直属总监奖金
	static String masterGrade = "BLF";//BLF：培养直属总经理奖金
	
	//推荐奖金等级
	static String memberToMemberAwardGrade = "AL20";//会员直推会员奖金
	static String vendorToMemberAwardGrade = "AL28";//代购直推会员奖金
	static String vendorAwardGrade = "ALA";//代购直推奖金
	static String directorAwardGrade = "ALB";//总监直推奖金
	static String masterAwardGrade = "ALC";//总经理直推奖金
	static String teamOfDirectorAwardGrade = "ALD";//直属团队总监推荐奖金
	static String teamOfSupDirectorAwardGrade = "ALE";//直属总监推荐奖金
	static String teamOfMasterAwardGrade = "ALF";//直属团队总经理推荐奖金
	static String teamOfSupMasterAwardGrade = "ALG";//直属总经理推荐奖金
	static String teamOfDirectorOfMasterAwardGrade = "ALH";//直属总监团队总经理推荐奖金
	
	
	static BigDecimal discountRate = BigDecimal.valueOf(0.9);//VIP折上折比例
	static BigDecimal nvbRate = BigDecimal.valueOf(1).subtract(discountRate);//普通用户购买的代购收益比例，=1-VIP折上折比例
	static BigDecimal vbRate = nvbRate.multiply(BigDecimal.valueOf(0.25));//VIP购买的代购收益比例，=(1-VIP折上折比例)*0.25
	
	static BigDecimal supVendorRate = BigDecimal.valueOf(0.25);//直属代购收益比例
	static BigDecimal teamRate = BigDecimal.valueOf(0.20);//团队非直属代购收益比例
	static BigDecimal directorRate = BigDecimal.valueOf(0.3);//总监收益比例
	static BigDecimal masterRate = BigDecimal.valueOf(0.3);//总经理收益比例
	
	//推荐奖金金额
	static BigDecimal memberToMemberAward = BigDecimal.valueOf(20);//会员推荐会员奖励（小程序端会员推会员）
	static BigDecimal vendorToMemberAward = BigDecimal.valueOf(28);//代购推荐会员奖励（app端代购用户）
//	static BigDecimal vendor2vendorAward = BigDecimal.valueOf(100);//代购推荐代购奖励（app端代购用户）
//	static BigDecimal director2memberAward = BigDecimal.valueOf(28);//总监推荐会员奖励（app端代购用户）
//	static BigDecimal director2vendorAward = BigDecimal.valueOf(200);//总监推荐代购奖励（app端代购用户）
//	static BigDecimal master2memberAward = BigDecimal.valueOf(28);//总经理推荐会员奖励（app端代购用户）
//	static BigDecimal master2vendorAward = BigDecimal.valueOf(250);//总经理推荐代购奖励（app端代购用户）
	static BigDecimal vendorAward = BigDecimal.valueOf(100);//代购直推奖金
	static BigDecimal directorAward = BigDecimal.valueOf(200);//总监直推奖金
	static BigDecimal masterAward = BigDecimal.valueOf(250);//总经理直推奖金
	static BigDecimal teamOfDirectorAward = BigDecimal.valueOf(100);//直属团队总监推荐奖金
	static BigDecimal teamOfSupDirectorAward = BigDecimal.valueOf(15);//直属总监推荐奖金
	static BigDecimal teamOfMasterAward = BigDecimal.valueOf(150);//直属团队总经理推荐奖金
	static BigDecimal teamOfDirectorOfMasterAward = BigDecimal.valueOf(50);//直属总监团队总经理推荐奖金
	static BigDecimal teamOfSupMasterAward = BigDecimal.valueOf(10);//直属总经理推荐奖金
	
	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Resource
	AccountIncomeMapper accountIncomeMapper;
	@Resource
	AccountBonusMapper accountBonusMapper;
	@Resource
	AccountAwardMapper accountAwardMapper;
	@Resource
	VendorMapper vendorMapper;
	@Resource
	MemberMapper memberMapper;
	@Resource 
	AppUserMapper appUserMapper;
	@Resource 
	WxUserMapper wxUserMapper;
	@Resource
	OrderMapper orderMapper;
	@Resource
	GoodsMapper goodsMapper;
	@Override
	public ResponseForm getIncome(RequestForm param) {
		ResponseForm result = new ResponseForm();
		@SuppressWarnings("unchecked")
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String wxUid = (String) paramMap.get("wxUid");
		try {
			if (!StringUtils.isNotBlank(wxUid)) {
				result.setStatus(false);
				result.setMessage(LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
//			AccountIncome wxUser = new AccountIncome();
//			wxUser.setWxUid(wxUid);
//			AccountIncome income = accountIncomeMapper.selectOne(wxUser);
//			
			BonusAccount bonusAccount = accountIncomeMapper.getBonusAccount(wxUid);
			result.setData(bonusAccount);
			result.setTotal(1);
		}
		catch(Exception e)
		{
			result.setStatus(false);
			log.error("获取佣金账户信息error,wxUid=" + wxUid, e);
		}
		return result;
	}

	@Override
//	public JSONObject getIncomeDetails(String wxUid,String fromDate,String toDate,int page,int size)
	public JSONObject getIncomeDetails(RequestForm param) {
		Map<String, Object> paramMap = (Map<String, Object>) param.getData();
		String wxUid = (String) paramMap.get("wxUid");
		int page = (Integer) paramMap.get("page");
		int size = (Integer) paramMap.get("size");
		String fromDate = null;
		String toDate = null;
		JSONObject result = new JSONObject();
		result.put("status", false);
		result.put("total", 0);
		try {
			int start = 0;
			if(size<1)
				size=10;//默认每页10条

			if(page<1)
				page = 1;//默认第1页
			start = (page-1)*size;
			
			if (!StringUtils.isNotBlank(wxUid)) {
				result.put("message", LogInfo.PARAM_ERROR);
				log.error(LogInfo.PARAM_ERROR);
				return result;
			}
			List<IncomeDetails> list = accountIncomeMapper.getIncomeDetailsList(wxUid, fromDate, toDate, start, size);
			result.put("status", true);
			result.put("data", list);
			result.put("total", list.size());
		}
		catch(Exception e)
		{
			log.error("获取佣金账户信息error,wxUid=" + wxUid, e);
			result.put("message", LogInfo.ERROR);
			return result;
		}
		return result;
	}
	@Override
//	@Transactional(rollbackFor = Exception.class)
	public int createVendorAccount(AppUser appUser) {
		if(appUser==null)return 0;
		int r = 0;
		try {
			Date now = sdf.parse(sdf.format(new Date()));
			
			String wxUid  = appUser.getWxUid();
			String inviteCode = appUser.getInviteCode();
			String parentInviteCode = appUser.getParentInviteCode();
			boolean seedUser = inviteCode.equals(parentInviteCode) ? true:false;
			String parentWxuid = wxUid;
			if(!seedUser)
			{
				//非种子用户则通过邀请码找用户的推荐人身份信息（有可能是种子用户，种子用户是顶级）
				AppUser parentParm = new AppUser();
				parentParm.setInviteCode(appUser.getParentInviteCode());
				AppUser parentUser = appUserMapper.selectOne(parentParm);//通过邀请码查找
				parentWxuid = parentUser.getWxUid();
			}
			
			//r1.不允许重复,r2.普通用户
			Vendor arg0 = new Vendor();
			arg0.setWxUid(wxUid);
			Vendor hasVendor = vendorMapper.selectOne(arg0);
			if(hasVendor!=null)
				if(wxUid.equals(hasVendor.getWxUid()))//已存在代购了
					return 0;
			
			//创建直属代购
			Vendor vendor =  new Vendor();
			vendor.setParentWxUid(parentWxuid);
			vendor.setWxUid(wxUid);
			vendor.setInviteCode(appUser.getInviteCode());
			vendor.setStatus(appUser.getUserStatus()+"");
//			vendor.setLevel(level);
			vendor.setCreateTime(now);
			r = vendorMapper.insert(vendor);
			
			//创建代购的佣金账户
			AccountIncome accountIncome = new AccountIncome();
			accountIncome.setWxUid(appUser.getWxUid());
			accountIncome.setParentWxUid(parentWxuid);
			accountIncome.setInviteCode(appUser.getInviteCode());
			accountIncome.setWeixinId(appUser.getWeixinId());
			accountIncome.setAlipayId(appUser.getAlipayId());
			accountIncome.setMobile(appUser.getVerifyPhone());
			accountIncome.setUserStatus(appUser.getUserStatus()+"");
			accountIncome.setCreateTime(now);
			if(r>0)
				r = accountIncomeMapper.insert(accountIncome);
			
			return r;
		}
		catch(Exception e)
		{
			log.error("创建佣金账户error,wxUid=" + appUser.getWxUid(), e);
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return 0;
	}
	@Override
	public int createBonus(String orderWxuid,String orderId,String tradeType) {
		int r = 0;
		if(orderWxuid==null || orderId== null || tradeType==null)return r;
		if("".equals(orderWxuid) || "".equals(orderId) || "".equals(tradeType))return r;

		try {
			Vendor vendor = new Vendor();//订单关联的代购
			//根据下单的客户端类型找出购买用户信息
			int buyerStatus =0;//下单用户身份，默认下单用户是普通用户
			boolean seedUser = false;//种子代购标识
			boolean selfBuying = false;//代购、总监、总经理自购标识
			if("APP".equals(tradeType))//app端用户下单
			{
				AppUser arg0 = new AppUser();
				arg0.setWxUid(orderWxuid);
				AppUser buyer = appUserMapper.selectOne(arg0);
				buyerStatus = buyer.getUserStatus();
				String inviteCode = buyer.getParentInviteCode();//app端用户（普通用户或会员）绑定代购的邀请码
				//APP端用户下单无代购邀请码的不计算佣金，直接跳出
				//可能是这两种情况：1）空降代购无上级代购（不太可能）
				if(inviteCode==null || "".equals(inviteCode)) return r;
				
				//找出订单关联的代购信息
				Vendor arg1 = new Vendor();
				arg1.setInviteCode(inviteCode);
				vendor = vendorMapper.selectOne(arg1);
			}
			else//JSAPI 小程序端用户下单
			{
				WxUser arg = new WxUser();
				arg.setWxUid(orderWxuid);
				WxUser buyer = wxUserMapper.selectOne(arg);
				buyerStatus = buyer.getUserStatus();
				String inviteCode = buyer.getInviteCode();//小程序端用户（普通用户或会员）绑定代购的邀请码
				//小程序端用户下单无代购邀请码的不计算佣金，直接跳出
				if(inviteCode==null || "".equals(inviteCode)) return r;
				
				//根据邀请码找出订单关联的代购信息
				Vendor arg1 = new Vendor();
				arg1.setInviteCode(inviteCode);
				vendor = vendorMapper.selectOne(arg1);

				//如果代购通过小程序自己购买自己分享的商品，算自购也无佣金。
				//通过邀请码判断是否是自购，
//				if(inviteCode.equals(vendor.getInviteCode())) //排除代购通过小程序端自购提佣
//					selfBuying =true;//代购自购如果直接退出，则导致代购的直属代购无法提佣了，因此按自购逻辑处理
				
			}
			//判断代购身份是否是种子用户
			if(vendor!=null)
			{
				if(vendor.getWxUid() !=null
					&& vendor.getParentWxUid() !=null
					&& vendor.getWxUid().equals(vendor.getParentWxUid()))
					seedUser = true;
			}
			//如果购买用户的身份是2:代购,3:总监,4:总经理其中之一，并且下单用户ID和推荐人用户ID一样，则该订单是代购自购
			////如果是自购，则该代购不返佣金，直属代购和总监和总经理正常享有团队奖金分成
			if(buyerStatus>1 
				&& buyerStatus<10 //排除ios苹果端游客身份
				&& orderWxuid.equals(vendor.getWxUid())//代购自己购买
				)
				selfBuying =true;

			//获取本次交易的佣金凭据
			List<BonusVoucher> dealResult = accountIncomeMapper.getDealResult(orderId);
			VendorTeam vendorTeam = getVendorTeam(vendor);//获取该代购团队销售佣金权益成员
			//根据销售佣金权益成员身份分配销售佣金
			r = saveBonusDetails(vendorTeam,orderWxuid,buyerStatus,selfBuying,dealResult);

		}
		catch(Exception e)
		{
			log.error("创建佣金明细error,wxUid=" + orderWxuid, e);
			return r;
		}
		return r;
	}
	@Override
	public int createVendorAward(AppUser appUser,String orderId) {
		int r = 0;
		if(appUser==null)return r;
		String wxUid = appUser.getWxUid();
		String parentInviteCode = appUser.getParentInviteCode();
		if(wxUid==null)return r;
		if(parentInviteCode==null || "".equals(parentInviteCode)) return r;//自然流量的用户无推荐人，必须要邀请码
		try {
			Date now = sdf.parse(sdf.format(new Date()));
			Vendor parentParm = new Vendor();
			parentParm.setInviteCode(parentInviteCode);
			Vendor vendor = vendorMapper.selectOne(parentParm);//通过邀请码查找推荐人
			

			//判断当前代购的身份是总监还是总经理
			boolean vendorIsVendor = "2".equals(vendor.getStatus())? true:false;
			boolean vendorIsDirector = "3".equals(vendor.getStatus())? true:false;
			boolean vendorIsMaster = "4".equals(vendor.getStatus())? true:false;			
			//==============================================================================start
			//第一部分奖金（直推/一级奖金）：代购、总监、总经理三种身份直接邀请直属代购获分别获得100、200、250
			if(vendorIsVendor==true)//代购自己邀请直属代购获100元
			{
				r = createAccountAward(vendor,orderId,vendorAwardGrade,vendorAward,now);
			}
			else if(vendorIsDirector==true)//总监自己邀请直属代购获200元
			{
				r = createAccountAward(vendor,orderId,directorAwardGrade,directorAward,now);
			}
			else if(vendorIsMaster==true)//总经理自己邀请直属代购获250元
			{
				r = createAccountAward(vendor,orderId,masterAwardGrade,masterAward,now);
			}
			//==============================================================================end

			VendorTeam vendorTeam = getVendorTeam(vendor);//获取该代购团队推荐奖金权益成员
			//==============================================================================start
			//第二部分奖金（二级推荐奖金）：代购推399，直属代购无奖金，直属团队总监100，直属总监15，总经理50，直属总经10
			if(vendorTeam.getTeamOfDirector() !=null)//直属团队总监100
			{
				//创建团队总监推荐奖励佣金100
				if(!vendor.getWxUid().equals(vendorTeam.getTeamOfDirector().getWxUid()))//总监身份拿完直推奖金不能再拿二级奖金了
					r = createAccountAward(vendorTeam.getTeamOfDirector()
							,orderId,teamOfDirectorAwardGrade,teamOfDirectorAward,now);
			}
			if(vendorTeam.getTeamOfSupDirector() !=null)//二级是直属总监
			{
				//创建直属总监推荐奖励佣金15
				r = createAccountAward(vendorTeam.getTeamOfSupDirector()
							,orderId,teamOfSupDirectorAwardGrade,teamOfSupDirectorAward,now);	
			}
			if(vendorTeam.getTeamOfMaster() !=null)//二级是总经理直属团队
			{
				
				if(vendorIsVendor==true && vendorTeam.getTeamOfDirector()==null)//总经理直属团队新增代购获150元
				{
					r = createAccountAward(vendorTeam.getTeamOfMaster()
							,orderId,teamOfMasterAwardGrade,teamOfMasterAward,now);
				}
				else
				{
					//创建直属总监推荐奖励佣金50
					if(!vendor.getWxUid().equals(vendorTeam.getTeamOfMaster().getWxUid()))//总经理身份拿完直推奖金不能再拿二级奖金了
						r = createAccountAward(vendorTeam.getTeamOfMaster()
								,orderId,teamOfDirectorOfMasterAwardGrade,teamOfDirectorOfMasterAward,now);
				}
			}
			if(vendorTeam.getTeamOfSupMaster() !=null)//二级是直属总经理
			{
				//创建直属总经理推荐奖励佣金10
				r = createAccountAward(vendorTeam.getTeamOfSupMaster()
						,orderId,teamOfSupMasterAwardGrade,teamOfSupMasterAward,now);
			}
			//==============================================================================end
		}
		catch(Exception e)
		{
			log.error("创建佣金账户error,wxUid=" + wxUid, e);
		}
		return r;
	}
	@Override
	public int createMemberAccount(String wxUid,String parentWxUid,String orderId) {
		if(wxUid==null||orderId==null)return 0;
		int r = 0;
		try {
			
			
//			String wxUid  = wxUser.getWxUid();
//			String inviteCode = wxUser.getInviteCode();
//			String parentWxuid = wxUser.getParentWxuid();
//			boolean seedUser = wxUid.equals(parentWxuid) ? true:false;
//			if(!seedUser)
//			{
//				//非种子用户则通过邀请码找用户的推荐人身份信息（有可能是种子用户，种子用户是顶级）
//				AppUser parentParm = new AppUser();
//				parentParm.setInviteCode(appUser.getParentInviteCode());
//				AppUser parentUser = appUserMapper.selectOne(parentParm);//通过邀请码查找
//				parentWxuid = parentUser.getWxUid();
//			}
			
			//r1.不允许重复,r2.普通用户
			Member arg0 = new Member();
			arg0.setWxUid(wxUid);
			Member hasPerson = memberMapper.selectOne(arg0);
			if(hasPerson!=null)
				if(wxUid.equals(hasPerson.getWxUid()))//会员已存在
					return 0;
			
			Date now = sdf.parse(sdf.format(new Date()));
			//创建会员关系
			Member member =  new Member();
			member.setParentWxUid(parentWxUid);
			member.setWxUid(wxUid);
			member.setStatus(1);
			member.setCreateTime(now);
			r = memberMapper.insert(member);
			
			//创建会员的佣金账户
			AccountIncome accountIncome = new AccountIncome();
			accountIncome.setWxUid(wxUid);
			accountIncome.setParentWxUid(parentWxUid);
//			accountIncome.setInviteCode(appUser.getInviteCode());
//			accountIncome.setWeixinId(appUser.getWeixinId());
//			accountIncome.setAlipayId(appUser.getAlipayId());
//			accountIncome.setMobile(appUser.getVerifyPhone());
			accountIncome.setUserStatus("1");
			accountIncome.setCreateTime(now);
			if(r>0)
				r = accountIncomeMapper.insert(accountIncome);
			
			return r;
		}
		catch(Exception e)
		{
			log.error("创建会员佣金账户error,wxUid=" + wxUid, e);
		}
		return 0;
	}
	public int createMemberAccount(AppUser appUser,String orderId) {
		if(appUser==null||orderId==null)return 0;
		int r = 0;
		String wxUid = appUser.getWxUid();
		try {
			String parentInviteCode = appUser.getParentInviteCode();
			//r1.不允许重复,r2.普通用户
			Member arg0 = new Member();
			arg0.setWxUid(wxUid);
			Member hasPerson = memberMapper.selectOne(arg0);
			if(hasPerson!=null)
				if(wxUid.equals(hasPerson.getWxUid()))//会员已存在
					return 0;
			
			AppUser arg1 = new AppUser();
			arg1.setInviteCode(parentInviteCode);
			AppUser parentMember = appUserMapper.selectOne(arg1);
			String parentWxUid = parentMember.getWxUid();
			
			Date now = sdf.parse(sdf.format(new Date()));
			//创建会员关系
			Member member =  new Member();
			member.setParentWxUid(parentWxUid);
			member.setWxUid(wxUid);
			member.setStatus(1);
			member.setCreateTime(now);
			r = memberMapper.insert(member);
			
			//创建会员的佣金账户
			AccountIncome accountIncome = new AccountIncome();
			accountIncome.setWxUid(wxUid);
			accountIncome.setParentWxUid(parentWxUid);
//			accountIncome.setInviteCode(appUser.getInviteCode());
//			accountIncome.setWeixinId(appUser.getWeixinId());
//			accountIncome.setAlipayId(appUser.getAlipayId());
//			accountIncome.setMobile(appUser.getVerifyPhone());
			accountIncome.setUserStatus("1");
			accountIncome.setCreateTime(now);
			if(r>0)
				r = accountIncomeMapper.insert(accountIncome);
			
			return r;
		}
		catch(Exception e)
		{
			log.error("创建会员佣金账户error,wxUid=" + wxUid, e);
		}
		return 0;
	}
	@Override
	public int createMemberAward(String wxUid, String parentWxUid, String orderId) {
		int r = 0;
		if(wxUid==null && parentWxUid==null) return r;
		if(wxUid!=null && (parentWxUid==null || "".equals(parentWxUid))) return r;//自然流量用户（无推荐人）购买88会员无奖励
		if(wxUid.equals(parentWxUid)) return r;//自己购买88无奖励
		try {
			//创建会员推荐奖励佣金
			Date now = sdf.parse(sdf.format(new Date()));
			AccountAward award = new AccountAward();//会员的奖金
			award.setWxUid(wxUid);
			award.setParentWxUid(parentWxUid);
			award.setOrderId(orderId);
			award.setIncomeGrade(memberToMemberAwardGrade);
			award.setIncomeAmount(memberToMemberAward);
			award.setIncomeDate(now);
			award.setCreateTime(now);
			accountAwardMapper.insert(award);
			
			//更新推荐人账号收益
			accountIncomeMapper.updateMemberPreIncomeAmount(parentWxUid, memberToMemberAward);
		}
		catch(Exception e)
		{
			log.error("创建会员佣金明细error,wxUid=" + wxUid, e);
		}
		return 0;
	}
	public int createMemberAward(AppUser appUser, String orderId) {
		int r = 0;
		if(appUser==null)return r;
//		if(wxUid!=null && (parentWxUid==null || "".equals(parentWxUid))) return r;//自然流量用户（无推荐人）购买88会员无奖励
//		if(wxUid.equals(parentWxUid)) return r;//自己购买88无奖励
		String wxUid = appUser.getWxUid();
		String parentInviteCode = appUser.getParentInviteCode();
		try {
			
			AppUser arg1 = new AppUser();
			arg1.setInviteCode(parentInviteCode);
			AppUser parentMember = appUserMapper.selectOne(arg1);
			String parentWxUid = parentMember.getWxUid();
			
			//创建会员推荐奖励佣金
			Date now = sdf.parse(sdf.format(new Date()));
			AccountAward award = new AccountAward();//代购推荐会员的奖金
			award.setWxUid(wxUid);
			award.setParentWxUid(parentWxUid);
			award.setOrderId(orderId);
			award.setIncomeGrade(vendorToMemberAwardGrade);
			award.setIncomeAmount(vendorToMemberAward);
			award.setIncomeDate(now);
			award.setCreateTime(now);
			accountAwardMapper.insert(award);
			
			//更新推荐人账号收益
			accountIncomeMapper.updateMemberPreIncomeAmount(parentWxUid, vendorToMemberAward);
		}
		catch(Exception e)
		{
			log.error("创建会员佣金明细error,wxUid=" + wxUid, e);
		}
		return 0;
	}
	private int saveBonusDetails(VendorTeam vendorTeam,String buyerWxuid,int buyerStatus, boolean selfBuying, List<BonusVoucher> dealResult)
	{
		int r = 0;
		try
		{
			Date now = sdf.parse(sdf.format(new Date()));
			String masterUid = "";
			for(BonusVoucher voucher:dealResult)
			{

				//根据购买用户身份计算佣金
				
				BigDecimal vendorAmount = BigDecimal.valueOf(0);//代购销售佣金，BLB奖金
				BigDecimal supVendorAmount = BigDecimal.valueOf(0);//直属代购奖金，BLC奖金
				BigDecimal teamAmount = BigDecimal.valueOf(0);//团队管理奖金，BLD奖金
				BigDecimal directorAmount = BigDecimal.valueOf(0);//培养直属总监奖金，BLE奖金
				BigDecimal masterAmount = BigDecimal.valueOf(0);//培养直属总经理奖金，BLF奖金
				
				BigDecimal incomeRate = BigDecimal.valueOf(1).subtract(voucher.getMemberRate());//nvbRate;//非会员（普通用户）购买的代购收益比例
				BigDecimal rebateAmount = voucher.getVipSaveAmount();//代购提成=折扣节省金额

				//根据购买用户身份判断提佣金的基数
				boolean isVipBuying = (buyerStatus==0 || buyerStatus==10) ? false:true;
				if(isVipBuying)//VIP购买
				{
					incomeRate = incomeRate.multiply(BigDecimal.valueOf(0.25));//vbRate;//会员用户购买的代购收益比例=(1-VIP折扣率)*0.25
					rebateAmount = rebateAmount.multiply(BigDecimal.valueOf(0.25));//代购提成=折扣节省金额*vbRate
				}
				
				//奖金金额计算
				vendorAmount = rebateAmount;//代购提成=折扣节省金额
				supVendorAmount = rebateAmount.multiply(supVendorRate);//直属代购收益金额
				teamAmount = rebateAmount.multiply(teamRate);//团队非直属代购奖金
				directorAmount = teamAmount.multiply(directorRate);//培养直属总监奖金
				masterAmount = teamAmount.multiply(masterRate);//培养直属总经理奖金

				//第一部分佣金：代购销售佣金分配================================start
				//分享赚钱：代购可享受销售商品获得佣金（5%-30%）
				//三种身份的分享赚钱收益：代购收益3、总监收益2、总经理收益2
				if(!selfBuying)//代购A自购，则A无销售提佣，直属代购正常提佣
				{
					r = createAccountBonus(masterUid,vendorTeam.getVendor()
							,vendorGrade,incomeRate,vendorAmount
							,buyerWxuid,buyerStatus,voucher,now);
				}
				//============================================================end
			
				//第二部分佣金：直属代购奖金分配=================================start
				//代购的收益4：获直属代购省钱和销售佣金收益25%
				//三种身份的直属代购收益：代购收益4、总监收益3、总经理收益3
				if(vendorTeam.getSupVendor()!=null)
				{
					r = createAccountBonus(masterUid,vendorTeam.getSupVendor()
							,supVendorGrade,supVendorRate,supVendorAmount
							,buyerWxuid,buyerStatus,voucher,now);
				}
				//============================================================end
				
				//第三部分佣金：团队管理奖金分配=================================start
				//获直属团队所有代购佣金收益20%（管理奖金）
				//权益身份：总监和总经理
				//条件1：所有代购每一单的销售佣金都需分20%给所在团队的总监。
				//条件2：所有总监每一单的销售佣金都需分20%给所在团队的总经理。
				boolean hasTeamAward = false;
				if(vendorTeam.getTeamOfDirector()!=null)
				{
					boolean vendorIsVendor = "2".equals(vendorTeam.getVendor().getStatus())? true:false;
					if(vendorIsVendor==true)
					{
						r = createAccountBonus(masterUid,vendorTeam.getTeamOfDirector()
							,teamGrade,teamRate,teamAmount
							,buyerWxuid,buyerStatus,voucher,now);
						hasTeamAward=true;
					}
				}
				if(vendorTeam.getTeamOfMaster()!=null)
				{
					//总经理获直属团队所有代购佣金收益（管理奖金）
//					boolean vendorIsVendor = "2".equals(vendorTeam.getVendor().getStatus())? true:false;
					boolean supVendorIsVendor = "2".equals(vendorTeam.getSupVendor().getStatus())? true:false;
					if(supVendorIsVendor == true && hasTeamAward == false)//团队奖金互斥
					{
						r = createAccountBonus(masterUid,vendorTeam.getTeamOfMaster()
							,teamGrade,teamRate,teamAmount
							,buyerWxuid,buyerStatus,voucher,now);
						hasTeamAward=true;
					}
					if(vendorTeam.getTeamOfDirector()!=null)//获团队所有总监管理奖金收益30%
						r = createAccountBonus(masterUid,vendorTeam.getTeamOfMaster()
								,masterGrade,masterRate,masterAmount
								,buyerWxuid,buyerStatus,voucher,now);
				}
				
				//总监的收益5：获直属育成总监管理奖金收益30%（不包括礼包销售佣金）
				//如果当前代购身份是总监且上级代购身份也是总监，则上级获得BLE奖金，
				if(vendorTeam.getTeamOfSupDirector()!=null)
				{
					if(hasTeamAward == true)//没有团队管理奖就不分配伯乐奖
						r = createAccountBonus(masterUid,vendorTeam.getTeamOfSupDirector()
							,directorGrade,directorRate,directorAmount
							,buyerWxuid,buyerStatus,voucher,now);
				}
				//总经理的收益10：获直接育成总经理管理奖金收益30%（不包括礼包销售佣金）
				//如果当前代购身份是总经理且上级代购身份也是总经理，则上级获得BLF奖金
				if(vendorTeam.getTeamOfSupMaster()!=null)
				{
					boolean supVendorIsMaster = "4".equals(vendorTeam.getSupVendor().getStatus())? true:false;
					if(supVendorIsMaster == true && hasTeamAward == true)//没有团队管理奖就不分配伯乐奖
						r = createAccountBonus(masterUid,vendorTeam.getTeamOfSupMaster()
							,masterGrade,masterRate,masterAmount
							,buyerWxuid,buyerStatus,voucher,now);
				}
			}
		}
		catch(Exception e)
		{
			log.error("创建转换交易信息error,orderId=" + "?", e);
			return -1;
		}
		return r;
	}
	/**
	 * 	写入佣金明细记录
	 * @param masterUid
	 * @param parentWxUid
	 * @param wxUid
	 * @param inviteCode
	 * @param buyerStatus
	 * @param incomeGrade
	 * @param incomeRate
	 * @param incomeAmount
	 * @param voucher
	 * @param now
	 * @return
	 */
	private int createAccountBonus(String masterUid,Vendor vendor
			,String incomeGrade,BigDecimal incomeRate,BigDecimal incomeAmount
			,String buyerWxuid,int buyerStatus,BonusVoucher voucher,Date now)
	{
		int r = 0;
		AccountBonus record = new AccountBonus();//佣金明细记录
		try {
			//计算代购销售佣金
//			record.setWxUid(wxUid);
//			record.setParentWxUid(parentWxUid);
//			record.setInviteCode(inviteCode);
//			record.setUserStatus(userStatus);
			record.setWxUid(vendor.getWxUid());
			record.setParentWxUid(vendor.getParentWxUid());
			record.setInviteCode(vendor.getInviteCode());
			record.setUserStatus(Integer.parseInt(vendor.getStatus()));
			record.setIncomeStatus(0);//默认预计收益状态，7天后无退款状态改成可提现状态1
			record.setIncomeGrade(incomeGrade);
			record.setIncomeRate(incomeRate);
			record.setIncomeAmount(incomeAmount);
//			vendorBonus.setIncomeDate(incomeDate);//7天后无退款记录确认时间
			record.setCreateTime(now);

			record.setOrderId(voucher.getOrderId());
			record.setGoodsId(voucher.getGoodsId());
			record.setGoodsQty(voucher.getGoodsQty());
			record.setDiscountRate(voucher.getDiscountRate());
			record.setDiscountPrice(voucher.getDiscountPrice());
			record.setMemberRate(voucher.getMemberRate());
			record.setMemberPrice(voucher.getMemberPrice());
			record.setVipSaveAmount(voucher.getVipSaveAmount());
			record.setDisplayContent(voucher.getDisplayContent());
			record.setBuyerWxUid(buyerWxuid);
			record.setBuyerStatus(buyerStatus);
			r = accountBonusMapper.insert(record);
			if(r>0)
				accountIncomeMapper.updatePreIncomeAmount(vendor.getWxUid(), incomeAmount);
		}
		catch(Exception e)
		{
			log.error("保存用户佣金记录error,buyerWxuid=" + buyerWxuid, e);
			return -1;
		}
		return r;
	}
	private int createAccountAward(Vendor vendor,String orderId,String incomeGrade,BigDecimal incomeAmount,Date now)
	{
		int r= 0;
		if(vendor==null)return r;
		try {
			//创建代购推荐奖励佣金
			AccountAward award = new AccountAward();//会员的奖金
			award.setWxUid(vendor.getWxUid());
			award.setParentWxUid(vendor.getParentWxUid());
			award.setOrderId(orderId);
			award.setIncomeGrade(incomeGrade);
			award.setIncomeAmount(incomeAmount);
			award.setIncomeDate(now);
			award.setCreateTime(now);
			r= accountAwardMapper.insert(award);
			if(r>0)
				accountIncomeMapper.updateVendorPreIncomeAmount(vendor.getWxUid(), incomeAmount);
		}catch(Exception e)
		{
			log.error("保存代购推荐奖金记录error,vendorWxuid=" + vendor.getWxUid(), e);
			return -1;
		}
		return r;
	}
	
	/**
	 * 	获取代购团队所属总监，递归算法
	 * @param vendor	代购
	 * @return	
	 */
	private Vendor getTeamOfDirector(Vendor vendor)
	{
		if(vendor==null) return vendor;
		try {
			Vendor arg0 = new Vendor();
			arg0.setWxUid(vendor.getParentWxUid());
			Vendor user =  vendorMapper.selectOne(arg0);
			if(user==null) return null;
			if(user.getStatus()==null) return null;
			if("4".equals(user.getStatus())) return null;//防止死循环
			if(user.getWxUid().equals(user.getParentWxUid())) return null;//增加约束条件防止错误数据导致无终止递归
			boolean isDirector = "3".equals(user.getStatus())? true:false;
			if(isDirector)
				return user;
			else
				return getTeamOfDirector(user);
		}
		catch(Exception e)
		{
			log.error("获取代购团队所属总监error,wxUid=" + vendor.getWxUid(), e);
		}
		return null;
	}
	/**
	 * 	获取代购团队所属总经理，递归算法
	 * @param vendor	代购
	 * @return	
	 */
	private Vendor getTeamOfMaster(Vendor vendor)
	{
		if(vendor==null) return vendor;
		try {
			Vendor arg0 = new Vendor();
			arg0.setWxUid(vendor.getParentWxUid());
			Vendor user =  vendorMapper.selectOne(arg0);
			if(user==null) return null;
			if(user.getStatus()==null) return null;
			if(user.getWxUid().equals(user.getParentWxUid())) return null;//增加约束条件防止错误数据导致无终止递归
			boolean isMaster = "4".equals(user.getStatus())? true:false;
			if(isMaster)
				return user;
			else
				return getTeamOfMaster(user);
		}
		catch(Exception e)
		{
			log.error("获取代购团队所属总监error,wxUid=" + vendor.getWxUid(), e);
		}
		return null;
	}
	
	public VendorTeam getVendorTeam(Vendor vendor)
	{
		if(vendor==null) return null;
		//1.构造代购团队对象，并设置团队的代购，如果是顶级代购，则代购团队只有自己并返回。
		VendorTeam vendorTeam = new VendorTeam(vendor);
		try {
			if(null == vendor.getParentWxUid()) return vendorTeam;
			boolean vendorIsRoot = (vendor.getParentWxUid().equals(vendor.getWxUid()))? true:false;
			if(vendorIsRoot == true) return vendorTeam;
			
			//2.1.查找直属代购，如果找到，则设置直属代购，否则返回
			Vendor arg0 = new Vendor();
			arg0.setWxUid(vendor.getParentWxUid());
			Vendor supVendor =  vendorMapper.selectOne(arg0);
			//2.2.设置直属代购
			vendorTeam.setSupVendor(supVendor);
			if(supVendor==null) return vendorTeam;
			if(null == supVendor.getParentWxUid() || null == supVendor.getStatus())return vendorTeam;//不允许无父节点或无身份的脏数据
//			if(supVendor.getParentWxUid().equals(supVendor.getWxUid())) return vendorTeam;//增加约束条件防止错误数据导致无终止递归

			//3.1.判断当前代购的身份是代购？是总监？还是总经理？还是顶级代购?
			boolean vendorIsVendor = "2".equals(vendor.getStatus())? true:false;
			boolean vendorIsDirector = "3".equals(vendor.getStatus())? true:false;
			boolean vendorIsMaster = "4".equals(vendor.getStatus())? true:false;
			//3.2.判断代购上级的身份是代购？是总监？是总经理？还是顶级代购?
			boolean supVendorIsVendor = "2".equals(supVendor.getStatus())? true:false;
			boolean supVendorIsDirector = "3".equals(supVendor.getStatus())? true:false;
			boolean supVendorIsMaster = "4".equals(supVendor.getStatus())? true:false;
			boolean supVendorIsRoot = supVendor.getParentWxUid().equals(supVendor.getWxUid())? true:false;
			
			//3.3.根据上下级关系，查找和设置直属团队总监
			//可能没找到，可能找到的是总监、或是总经理、或是顶级代购
			Vendor teamOfDirector=null;
			Vendor teamOfMaster=null;
			boolean hasTeamOfDirector=false;
			boolean hasTeamOfMaster=false;
//			if(supVendorIsRoot == true) return vendorTeam;
			
			if(vendorIsVendor == true && supVendorIsDirector == true)//如果是代购和总监关系
			{
				teamOfDirector = supVendor;//设置当前代购为直属团队总监
				hasTeamOfDirector=true;
			}
			else if(vendorIsVendor == true && supVendorIsVendor == true)//如果是代购和代购关系
			{
				teamOfDirector = getTeamOfDirector(supVendor);//继续找出直属团队总监
				hasTeamOfDirector = teamOfDirector!=null? true:false;
			}
			else if(vendorIsVendor == true && supVendorIsMaster == true)//如果是代购和总经理关系
			{
				teamOfMaster = supVendor;//当前代购设置为直属团队总经理
				hasTeamOfMaster = true;
			}
			else if(vendorIsDirector == true && supVendorIsDirector == true)//如果是总监和总监关系
			{
				teamOfMaster = getTeamOfMaster(supVendor);//找出总监团队的总经理
				if(teamOfMaster!=null)
					hasTeamOfMaster = true;
			}
			else if(vendorIsDirector == true && supVendorIsMaster == true)//如果是总监和总经理关系
			{
				teamOfMaster = supVendor;//当前代购设置为直属团队总经理
				hasTeamOfMaster = true;
			}
			else if(vendorIsMaster == true && supVendorIsMaster == true)//如果是总经理和总经理关系
			{
				teamOfMaster = vendor;//当前代购设置为直属团队总经理
				hasTeamOfMaster = true;
			}
			//3.4.设置直属团队总监
			vendorTeam.setTeamOfDirector(teamOfDirector);
			
			//4.1.查找直属团队总监的上级
			Vendor teamOfSupDirector=null;
			boolean hasTeamOfSupDirector = false;
			if(hasTeamOfDirector == true)
			{
				Vendor arg1 = new Vendor();
				arg1.setWxUid(teamOfDirector.getParentWxUid());
				teamOfSupDirector = vendorMapper.selectOne(arg1);
				hasTeamOfSupDirector = teamOfSupDirector!=null? true:false;
			}
			//4.2.如果直属团队总监上级的身份是总监，则是直属总监关系，否则还可能是总监或总经理或顶级总经理
			boolean isTeamOfSupDirector = false;
			boolean isTeamOfMaster = false;
			boolean teamOfSupDirectorIsRoot = false;
			if(hasTeamOfSupDirector==true)
			{
				isTeamOfSupDirector = "3".equals(teamOfSupDirector.getStatus())? true:false;
				isTeamOfMaster = "4".equals(teamOfSupDirector.getStatus())? true:false;
				teamOfSupDirectorIsRoot = teamOfSupDirector.getWxUid()
							.equals(teamOfSupDirector.getParentWxUid())
							&& isTeamOfMaster==true? true:false;
			}
			//4.3.根据身份设置直属团队总监的上级，并决定继续找出团队直属总经理
			
			if(teamOfSupDirectorIsRoot==true)
			{
				teamOfMaster = teamOfSupDirector;
				vendorTeam.setTeamOfMaster(teamOfMaster);
				return vendorTeam;
			}
			else if(isTeamOfMaster==true)
			{
				teamOfMaster = teamOfSupDirector;
			}
			else if(isTeamOfSupDirector==true)
			{
				vendorTeam.setTeamOfSupDirector(teamOfSupDirector);
				teamOfMaster = getTeamOfMaster(teamOfSupDirector);
			}
			//5.直属团队总经理
			vendorTeam.setTeamOfMaster(teamOfMaster);
			if(null== teamOfMaster) return vendorTeam;

			//6.团队总经理的直属总经理
			Vendor arg2 = new Vendor();
			arg2.setWxUid(teamOfMaster.getParentWxUid());
			Vendor teamOfSupMaster = vendorMapper.selectOne(arg2);
			if(null==teamOfSupMaster)return vendorTeam;
			boolean isTeamOfSupMaster = "4".equals(teamOfSupMaster.getStatus())? true:false;
			if(isTeamOfSupMaster)
				vendorTeam.setTeamOfSupMaster(teamOfSupMaster);
			return vendorTeam;
		}
		catch(Exception e)
		{
			log.error("获取代购团队所属总监error,wxUid=" + vendor.getWxUid(), e);
		}
		return vendorTeam;		
	}
}
